#include "SimpleTimer.h"


UINT SimpleTimer::instanceID = 0;
map<UINT, SimpleTimer*> SimpleTimer::instances;

SimpleTimer::SimpleTimer(HWND hWnd)
{
	this->hWnd = hWnd;
	timerID = ++instanceID;
	tag = 0;
	interval = 100;
	running = false;	
	onTickPtr = 0;
}

SimpleTimer::~SimpleTimer()
{
	Stop();
}


void SimpleTimer::Tick(TickProc ptr)
{
	onTickPtr = ptr;
}

void SimpleTimer::Start()
{
	if (running)
		return;

	if (!interval)
		return;

	if (!hWnd)
		timerID = SetTimer(0, 0, interval, TimerProc);
	else
		SetTimer(hWnd, timerID, interval, TimerProc);

	instances[timerID] = this;
	running = true;
}

void SimpleTimer::Stop()
{
	if (!running)
		return;

	KillTimer(hWnd, timerID);

	running = false;
}

void SimpleTimer::SetInterval(UINT interval)
{
	this->interval = interval;
}

UINT SimpleTimer::GetInterval()
{
	return this->interval;
}
	
bool SimpleTimer::IsRunning()
{
	return running;
}

void SimpleTimer::SetTag(LPVOID tag)
{
	this->tag = tag;
}

LPVOID SimpleTimer::GetTag()
{
	return tag;
}


VOID CALLBACK SimpleTimer::TimerProc(HWND hWnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
{
	if (instances.find(idEvent) != instances.end())
	{
		SimpleTimer* instance = instances[idEvent];
		
		if (instance->onTickPtr)
			instance->onTickPtr(instance, hWnd, idEvent, dwTime);
	}
}